/*
 * Copyright (C) 2014 singwhatiwanna(任玉刚) <singwhatiwanna@gmail.com>
 *
 * collaborator:田啸,宋思宇,Mr.Simple
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.aube.rvi.module;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.view.LayoutInflater;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import dalvik.system.DexClassLoader;

public class DLPluginManager {

    private static final String TAG = "DLPluginManager";

    private static DLPluginManager sInstance;
    private Context mContext;

    private String mNativeLibDir = null;
    private final HashMap<String, DLPluginPackage> mPackagesHolder = new HashMap<>();

    private DLPluginManager(Context context) {
        mContext = context.getApplicationContext();
        mNativeLibDir = mContext.getDir("pluginlib", Context.MODE_PRIVATE).getAbsolutePath();
    }

    public static DLPluginManager getInstance(Context context) {
        if (sInstance == null) {
            synchronized (DLPluginManager.class) {
                if (sInstance == null) {
                    sInstance = new DLPluginManager(context);
                }
            }
        }

        return sInstance;
    }

    /**
     * Load a apk. Before start a plugin Activity, we should do this first.<br/>
     * NOTE : will only be called by host apk.
     * 
     * @param dexPath
     */
    public DLPluginPackage loadApk(final String dexPath, String typeCode) {
        PackageInfo packageInfo = mContext.getPackageManager().getPackageArchiveInfo(dexPath,
                PackageManager.GET_ACTIVITIES | PackageManager.GET_SERVICES);
        if (packageInfo == null) {
            return null;
        }

        clearCachedConstructors(packageInfo);

        DLPluginPackage pluginPackage = preparePluginEnv(packageInfo, dexPath, typeCode);

        return pluginPackage;
    }

    /**
     * 清除LayoutInflater的sConstructorMap
     * @param packageInfo
     */
    private void clearCachedConstructors(PackageInfo packageInfo) {
        try {
            String packageName = packageInfo.packageName;
            LayoutInflater inflater = LayoutInflater.from(mContext);
            Class clazz = inflater.getClass();
            String className = clazz.getName();
            while (!className.equalsIgnoreCase("android.view.LayoutInflater")) {
                clazz = clazz.getSuperclass();
                className = clazz.getName();
            }
            Field fields = clazz.getDeclaredField("sConstructorMap");
            fields.setAccessible(true);
            HashMap<String, Constructor> values = (HashMap<String, Constructor>) fields.get(inflater);

            Iterator<Map.Entry<String, Constructor>> iterator = values.entrySet().iterator();
            List<String> removedKey = new ArrayList<>();
            while (iterator.hasNext()) {
                Map.Entry<String, Constructor> item = iterator.next();

                if(item.getKey().contains(packageName)) {
                    removedKey.add(item.getKey());
                }
            }
            for(String s : removedKey)
                values.remove(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * prepare plugin runtime env, has DexClassLoader, Resources, and so on.
     * 
     * @param packageInfo
     * @param dexPath
     * @return
     */
    private DLPluginPackage preparePluginEnv(PackageInfo packageInfo, String dexPath, String typeCode) {
        String key = packageInfo.packageName + "_" + typeCode;
//        DLPluginPackage pluginPackage = mPackagesHolder.get(packageInfo.packageName);
        DLPluginPackage pluginPackage = mPackagesHolder.get(key);
        if (pluginPackage != null) {
            if(packageInfo.versionCode <= pluginPackage.getVersionCode())
                return pluginPackage;
            mPackagesHolder.remove(key);
        }
        DexClassLoader dexClassLoader = createDexClassLoader(dexPath);
        AssetManager assetManager = createAssetManager(dexPath);
        Resources resources = createResources(assetManager);
        // create pluginPackage
        pluginPackage = new DLPluginPackage(dexClassLoader, resources, packageInfo);
//        mPackagesHolder.put(packageInfo.packageName, pluginPackage);
        mPackagesHolder.put(key, pluginPackage);
        return pluginPackage;
    }

    private String dexOutputPath;

    private DexClassLoader createDexClassLoader(String dexPath) {
        File dexOutputDir = mContext.getDir("dex", Context.MODE_PRIVATE);
        dexOutputPath = dexOutputDir.getAbsolutePath();
        DexClassLoader loader = new DexClassLoader(dexPath, dexOutputPath, mNativeLibDir, mContext.getClassLoader());
        return loader;
    }

    private AssetManager createAssetManager(String dexPath) {
        try {
            AssetManager assetManager = AssetManager.class.newInstance();
            Method addAssetPath = assetManager.getClass().getMethod("addAssetPath", String.class);
            addAssetPath.invoke(assetManager, dexPath);
            return assetManager;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public DLPluginPackage getPackage(String packageName) {
        return mPackagesHolder.get(packageName);
    }

    private Resources createResources(AssetManager assetManager) {
        Resources superRes = mContext.getResources();
        Resources resources = new Resources(assetManager, superRes.getDisplayMetrics(), superRes.getConfiguration());
        return resources;
    }

}
